using UnityEngine;
using System.Collections;

public class DoMyRay : MonoBehaviour
{

	private RaycastHit hit = new RaycastHit ();
	private GameObject gameObjectHit;

	void Update ()
	{
		//This generates our ray. We input the positions x, and y, as screen height and width divided by two to send a ray towards whatever the
		//screen center is viewing.
		//Camera.main is a static var, capable of being accessed from any code without references.
		Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
		
		
		//This defines a RaycastHit object. Its information is filled out if Physics.Raycasthit actually hits.
//		RaycastHit hit = new RaycastHit ();
		
		//This uses the ray's parameters to call physics.raycast. Mathf.Infinity is the distance the raycast will go before giving up. [Don't worry, distances of this size cause no lag].
		//We specify 'out' as that is just how c# rolls. [It goes into variable references, ETC. All of this is automagic in JS]
		
		if (Physics.Raycast (ray.origin, ray.direction, out hit, Mathf.Infinity)) {
		
			//This is not necissarry. All it does is visualize in 3D what the camera is looking at. hit.Distance is how far the raycast got before
			//Hittign soemthing. It functions as how far away we will draw the ray.
			Debug.DrawRay (ray.origin, ray.direction * hit.distance, Color.red);
			
			gameObjectHit = hit.collider.gameObject;
			
			if(gameObjectHit.tag.Equals("slab"))
				gameObject.transform.localScale = gameObject.transform.localScale / 2;
				
			/*
			Mesh mesh = hit.collider.GetComponent<MeshCollider>().sharedMesh;
			Vector3[] vertices = mesh.vertices;
    		int[] triangles = mesh.triangles;
			Vector3[] normals = mesh.normals;
			
			// Extract local space vertices that were hit
		    Vector3 p0 = vertices[triangles[hit.triangleIndex * 3 + 0]];
		    Vector3 p1 = vertices[triangles[hit.triangleIndex * 3 + 1]];    
		    Vector3 p2 = vertices[triangles[hit.triangleIndex * 3 + 2]];   
		
			Vector3 n0 = normals[triangles[hit.triangleIndex * 3 + 0]];
			
		    // Transform local space vertices to world space
		    Transform hitTransform  = hit.collider.transform;
		    p0 = hitTransform.TransformPoint(p0);
		    p1 = hitTransform.TransformPoint(p1);
		    p2 = hitTransform.TransformPoint(p2);
		    n0 = hitTransform.TransformDirection(n0);
			
			Debug.DrawRay(p0, n0, Color.green);
			
			// Display with Debug.DrawLine
		    Debug.DrawLine(p0, p1);
		    Debug.DrawLine(p1, p2);
		    Debug.DrawLine(p2, p0);*/
			//This is the index of the tri the camera is looking at:
//			int ind = hit.triangleIndex;
//			Debug.Log ("Hit tri index is " + ind * 3);
			
		}
	}
	
	void OnDrawGizmos () {
		Debug.DrawRay(hit.point, hit.normal, Color.magenta);
	}
}
